package yao.config;

import java.util.List;

import org.dom4j.Element;

import yao.config.exception.ConfigException;
import yao.config.exception.ConfigSettingException;


/**
 * XML节点转换成原始节点对象
 * 
 * @author YaoMing
 */
final class Element2ValueMap {

	/**
	 * 从Element中拿Node对象
	 * 
	 * @param e
	 * @return
	 * @throws ConfigException
	 * @throws ConfigSettingException
	 */
	static ValueMap element2ValueMap(Element e) throws ConfigSettingException {
		List<?> eEntrys = e.elements(PathContants.ENTRY);
		ValueMap valueMap = new ValueMap();
		for (Object o : eEntrys) {
			Element eEntry = (Element) o;
			String key = eEntry.attributeValue(PathContants.KEY);
			String value = eEntry.attributeValue(PathContants.VALUE);

			if (null == key) {
				Element eKey = eEntry.element(PathContants.KEY);
				key = null != eKey ? eKey.getText() : key;
			}
			if (null == key || key.equals("")) {
				throw new ConfigSettingException("Key can not be empty in value-map.");
			}

			if (null == value) {
				Element eValue = eEntry.element(PathContants.VALUE);
				value = null != eValue ? eValue.getText() : value;
			}

			valueMap.put$(key, new Value(value));
		}

		return valueMap;
	}
}
